package com.cty.Stack;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
/*
*
* 用来计算逆波兰表达式
*
* */
public class PolandNotation {
    public static void main(String[] args) {
        //(3+4)*5-6
        String expression = "3 4 + 5 * 6 -";
        List<String> list = new ArrayList<>(20);
        String[] elemList = expression.split(" ");
        //将元素存入集合
        for (String  elem: elemList) {
            list.add(elem);
        }
        int calculator = PolandNotation.calculator(list);
        System.out.println("表达式结果是：" + calculator);
    }
    //写一个计算方法
    public static int calculator(List<String> list) {
        Stack<Integer> stack = new Stack<>();
        int num1;
        int num2;
        int res;
        for (String elem : list) {
            if (isOper(elem)) {
                num1 = stack.pop();
                num2 = stack.pop();
                switch (elem) {
                    case "+":
                       res = num1 + num2;
                       break;
                    case "-":
                        res = num2 - num1;
                        break;
                    case "*" :
                        res = num1 * num2;
                        break;
                    case "/" :
                        res = num2 / num1;
                        break;
                    default:
                        throw new RuntimeException("表达式不正确！");
                }
                stack.push(res);
            } else {
                stack.push(Integer.parseInt(elem));
            }
        }
        return stack.pop();
    }
    //写一个判断符号的方法
    public static boolean isOper(String elem) {
        return elem.equals("+") || elem.equals("-") || elem.equals("*") || elem.equals("/");
    }
}
